<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col :span="4">
          <el-button type="success" @click="addFn" class="searchBtn"
            >新增角色</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="roleList" style="width: 100%" border stripe>
        <el-table-column type="expand" label="#">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
              class="vcenter"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二，三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限  -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop']"
                  class="vcenter"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="180"> </el-table-column>
        <el-table-column prop="roleName" label="roleName" width="180">
        </el-table-column>
        <el-table-column prop="roleDesc" label="roleDesc"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editFn(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row.id)"
            ></el-button>

            <el-tooltip
              class="item"
              effect="dark"
              content="权限分配"
              placement="top-start"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增弹框 -->
    <el-dialog
      title="新增角色"
      :visible.sync="addFlag"
      width="50%"
      :show-close="false"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="addForm.roleName"
            auto-complete="off"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input
            v-model="addForm.roleDesc"
            auto-complete="off"
            placeholder="请输入角色描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetAddFormFn('addFormRef')">取 消</el-button>
        <el-button type="primary" @click="addSaveFn('addFormRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 编辑弹框 -->
    <el-dialog
      :title="'编辑角色 - [ID:' + editForm.roleId + ']'"
      :visible.sync="editFlag"
      width="50%"
      :show-close="false"
    >
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editRoleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="editForm.roleName"
            auto-complete="off"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input
            v-model="editForm.roleDesc"
            auto-complete="off"
            placeholder="请输入角色描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetEditFormFn('editRoleFormRef')">取 消</el-button>
        <el-button type="primary" @click="editSaveFn('editRoleFormRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightFlag"
      width="50%"
      @close="setRightDialogClose"
    >
      <!-- 树形组件
    show-checkbox:显示复选框
    node-key:设置选中节点对应的值
    default-expand-all:是否默认展开所有节点
    :default-checked-keys 设置默认选中项的数组
    ref:设置引用 -->
      <el-tree
        :data="rights"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightFlag = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRolesAPI,
  deleteRolesByIdAPI,
  deleteRolesRightsByIdAPI,
  addRolesAPI,
  editRoleByIDAPI,
  getRightsAPI,
  setRoleRightsAPI
} from '@/api'
export default {
  data() {
    return {
      roleList: [],
      addFlag: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      editFlag: false,
      editForm: {
        roleId: 0,
        roleName: '',
        roleDesc: ''
      },
      setRightFlag: false,
      rights: [],
      treeProps: {
        // 通过label设置树形节点文本展示authName
        label: 'authName',
        // 设置通过children属性展示子节点信息
        children: 'children'
      },
      // 设置树形控件中默认选中的内容
      defKeys: [],
      // 保存正在操作的角色id
      roleId: ''
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    // 新增角色 ==》 打开弹框
    addFn() {
      this.addFlag = true
    },
    // 新增保存
    addSaveFn(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        const { data: res } = await addRolesAPI({
          ...this.addForm
        })
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)

        this.$message({
          message: res.meta.msg,
          type: 'success'
        })
        this.resetAddFormFn(formName)
        this.getRoles()
      })
    },
    resetAddFormFn(formName) {
      // 表单按钮重置k
      this.$refs[formName].resetFields()
      this.addFlag = false
    },

    async getRoles() {
      const { data: res } = await getRolesAPI()
      // console.log(res)
      this.roleList = res.data
    },
    editFn(row) {
      // console.log(row)
      this.editFlag = true
      this.editForm.roleId = row.id
      this.editForm.roleName = row.roleName
      this.editForm.roleDesc = row.roleDesc
    },

    resetEditFormFn(formname) {
      this.editForm.roleId = -1
      this.editForm.roleName = ''
      this.editForm.roleDesc = ''
      this.editFlag = false
    },

    editSaveFn(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        const { data: res } = await editRoleByIDAPI({
          ...this.editForm
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('编辑失败')

        this.$message({
          message: '角色编辑成功',
          type: 'success'
        })
        this.resetEditFormFn(formName)
        this.getRoles()
      })
    },

    // 删除角色
    async removeById(roleId) {
      const confirmResult = await this.$confirm(
        '请问是否要删除该角色',
        '删除提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') return this.$message.info('已经取消删除')

      // 用户点击了确定表示真的要删除
      // 当发送delete请求之后，返回的数据就是最新的角色权限信息
      const { data: res } = await deleteRolesByIdAPI(roleId)

      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除角色权失败')
      this.$message.success('删除角色权成功')
      this.getRoles()
    },

    // 删除角色权限
    async removeRightById(row, rightId) {
      // 弹窗提示用户是否要删除
      const confirmResult = await this.$confirm(
        '请问是否要删除该权限',
        '删除提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果用户点击确认，则confirmResult 为'confirm'
      // 如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }

      // console.log(row.id, rightId)

      // 用户点击了确定表示真的要删除
      // 当发送delete请求之后，返回的数据就是最新的角色权限信息
      const { data: res } = await deleteRolesRightsByIdAPI(row.id, rightId)

      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色权限失败')
      }

      // 无需再重新加载所有权限
      // 只需要对现有的角色权限进行更新即可
      row.children = res.data
      // this.getRoleList();
    },
    // 分配权限
    async showSetRightDialog(row) {
      // 将role.id保存起来以供保存权限时使用
      this.roleId = row.id
      // 获取所有权限的数据
      const { data: res } = await getRightsAPI('tree')
      // 如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$message.error('获取权限树失败')
      // 如果返回状态正常，将请求的数据保存在data中
      this.rights = res.data

      // 调用getLeafKeys进行递归，将三级权限添加到数组中
      this.getLeafKeys(row, this.defKeys)
      // 当点击分配权限按钮时，展示对应的对话框
      this.setRightFlag = true
      // console.log(this.defKeys)
    },
    getLeafKeys(node, arr) {
      // 该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      // 如果当前节点不包含children属性，则表示node为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      // 递归调用
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightDialogClose() {
      this.defKeys = []
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 将数组转换为 , 拼接的字符串
      const idStr = keys.join(',')

      // console.log(idStr)

      // 发送请求完成更新
      const { data: res } = await setRoleRightsAPI({
        roleId: this.roleId,
        rids: idStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }

      this.$message.success('分配权限成功')
      this.getRoles()
      // 关闭对话框
      this.setRightFlag = false
    }
  }
}
</script>

<style scoped>
.vcenter {
  display: flex;
  align-items: center;
}

.bdtop {
  border-top: 1px solid gray;
  padding: 5px 0px;
}
.bdbottom {
  border-bottom: 1px solid red;
  padding: 5px 0;
}

.el-tag {
  margin: 5px;
}
</style>
